package com.StartGame;

import java.io.*;
import java.util.*;

import android.content.*;
import android.content.res.*;
import android.graphics.*;
import android.net.*;
import android.provider.MediaStore.Images;
import android.util.*;
import android.view.*;
import android.view.SurfaceHolder.Callback;

public class MyGameView extends SurfaceView implements Callback {

	GameThread 	  mThread;				// GameThread
	SurfaceHolder mHolder;				// SurfaceHolder 
	static Context 	  mContext;			// Context 
	
	static int backGround;
	int imageType;						// Slice �̹��� ����
	int imageId;						// Slice �̹��� Id
	int storageType;					// �̹��� ���� ��ü
	
	static int Width, Height;			// View�� ũ��
	static int mgnLeft, mgnTop;			// 좌, 상 여백
	static int sMax;					// Slice 최대개수 
	static int Cnt;				// Slice 개수
	static int gSize;			// GameBoard Size
	static int sSize;			// Slice Size
	int stageNum;						// �������� ��ȣ
	int sliceNum[] = new int[36];		// Slice ��ȣ - �ִ� 6*6
	
	Slice mSlice[] = new Slice[36]; 	// Slice
	Score mScore;						// ���� ó����
	Rect mRect = new Rect();			// ���� ��ü ���� - Touch�� ����
	
	static Bitmap imgOrg;				// �� �̹���
	Bitmap imgBack;	// ��� �̹���
	
	static long startTime;				// �������� ���� �ð�
	int msgNum;							// �޽��� ��ȣ
	Bitmap imgMsg[] = new Bitmap[6];	// �޽���

	//-------------------------------------
	//  ����
	//-------------------------------------
	public MyGameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		
		mHolder = holder;		// holder�� Context ����
		mContext = context;
		mThread = new GameThread(holder, context);

		// Options Menu�� �� ���� �б�
		Cnt = ((GlobalVars) context.getApplicationContext()).getXCount();

		// ImageType �б�
		imageType = ((GlobalVars) mContext.getApplicationContext()).getImageType();
		imageId = ((GlobalVars) mContext.getApplicationContext()).getImageId();
		storageType = ((GlobalVars) mContext.getApplicationContext()).getStorageType();
		
		stageNum = 0;			// �������� ��ȣ
		
		InitGame();				// Start game
		MakeStage();			// Make Stage

		setFocusable(true);
		Log.v("surface Created", "---------------------------");
	}

	private void InitGame() {
		Display display = ((WindowManager) mContext.getSystemService (Context.WINDOW_SERVICE)).getDefaultDisplay();
		
		//GameBoard Size
		mgnLeft = 60;
		mgnTop = 120;
		
		gSize = display.getWidth() -  mgnLeft * 2;
		
		// Rect for Touch
		mRect.set(mgnLeft, mgnTop, mgnLeft + gSize, mgnTop + gSize);
		mScore = new Score();
		
		// �޽��� �̹��� �б�
		for (int i = 0; i < 5; i++)	{	
			// �޽��� ��ȣ�� 1���� ����
			imgMsg[i + 1] = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.msg1 + i);
		}	
	}
	
	//-------------------------------------
	//  Make Stage
	//-------------------------------------
	private void MakeStage() {
		sMax = Cnt * Cnt;				// Slice Total Number
		sSize = gSize / Cnt;
		
		// Allocate Num to Slice
		for (int i = 0; i < sMax; i++) { 
			sliceNum[i] = i;
		}

		LoadImages();	// �� ����  Trimming
		Shuffling();	// Slice ��ȣ ���� ���Ἲ ����
		
		// Slice()�� �迭�� �ֱ�
		for (int i = 0; i < sMax; i++) {
			mSlice[i] = null;	// �������� ���� ���� clear
			mSlice[i] = new Slice(sliceNum[i], i);
		}
		
		startTime = System.currentTimeMillis();
		mScore.MakeStageNum(stageNum);
		mScore.MakeTime(startTime);
	}
	
	//-------------------------------------
    //  LoadImage & Rescale - MakeStage���� ȣ��
    //-------------------------------------
	public void LoadImages() {
		Resources res = mContext.getResources();
		
		// �������� ��ȣ�� �´� ��� �̹��� �а� View�� ũ��� Rescale
		imgBack = BitmapFactory.decodeResource(res, R.drawable.background);
		imgBack = Bitmap.createScaledBitmap(imgBack, Width, Height, true);	

		// �� �̹��� �б�
		Bitmap imgtmp = BitmapFactory.decodeResource(res, R.drawable.img_gameboard);
		imgOrg = Bitmap.createScaledBitmap(imgtmp, gSize, gSize, true);	
	}

	
	//-------------------------------------
	//  Slice Shuffling - In MakeStage()
	//-------------------------------------
	public void Shuffling() {
		int r, t;
		Random rnd = new Random();
		for (int i = 0; i < sMax; i++) {
			r = rnd.nextInt(sMax);		// 0 ~ x*y-1
			t = sliceNum[i];			// ���� ��ġ�� ������ġ ��ȯ
			sliceNum[i] = sliceNum[r];
			sliceNum[r] = t;
		} // for
	} // Shuffle

	
	//-------------------------------------
    //  ���� �������� - Thread���� ȣ��
    //-------------------------------------
	public void MakeNextStage() {
		PauseGame();		// ������ �Ͻ� ����
		stageNum++; 

		MakeStage();
		ResumeGame();		// ������ �� �⵿
	}
	
	//-------------------------------------
    //  SurfaceView�� ��� �� ����Ǵ� �κ�
    //-------------------------------------
	public void surfaceCreated(SurfaceHolder holder) {
		Log.v("surface Started", "---------------------------");
		try {
			mThread.start();
		} catch (Exception e) {
			RestartGame(); 
		}
	}

	//-------------------------------------
    //  SurfaceView�� �ٲ� �� ����Ǵ� �κ�
    //-------------------------------------
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		Log.v("surface Changed", "---------------------------");
	}

	//-------------------------------------
    public void surfaceDestroyed(SurfaceHolder holder) {
		Log.v("surface Destroyed", "---------------------------");
		mThread.StopThread();
		Log.v("Save Stage", "---------------------------");
	}
	
	//-------------------------------------
	//  ������ ���� ����
	//-------------------------------------
	public void StopGame() {
		mThread.StopThread(); 
	}

	//-------------------------------------
	//  ������ �Ͻ� ����
	//-------------------------------------
	public void PauseGame() {
		mThread.PauseNResume(true); 
	}

	//-------------------------------------
	//  ������ ��⵿
	//-------------------------------------
	public void ResumeGame() {
		mThread.PauseNResume(false); 
	}

	//-------------------------------------
	//  ���� �ʱ�ȭ
	//-------------------------------------
	public void RestartGame() {
		mThread.StopThread();		// ������ ����

		// ������ �����带 ���� �ٽ� ��
	    mThread = null;	  
		mThread = new GameThread(mHolder, mContext); 
		mThread.start(); 
	}

//----------------------------------------------------------------
	
	//-------------------------------------
	//  GameThread Class
	//-------------------------------------
	class GameThread extends Thread {
		boolean canRun = true;			// ������ �����
		boolean isWait = false;
			
		
		Random rnd = new Random();
		int msgLoop = 0;			// ���� ī����
		boolean isNext = false;		// ���� ���������� ����
		
		//-------------------------------------
		//  ���� 
		//-------------------------------------
		public GameThread(SurfaceHolder holder, Context context) {
			
		}
		

		//-------------------------------------
		//  �ȳ� ���ڿ� ��� - run()���� ȣ��
		//-------------------------------------
		public void DrawMessage(Canvas canvas) {
			msgLoop++;
			if (msgLoop % 10 / 5 == 0) {
				int left = (Width - imgMsg[msgNum].getWidth()) / 2;
				canvas.drawBitmap(imgMsg[msgNum], left, Height - 90, null); 
			}	
			
			if (msgLoop >= 25) {				// �޽��� ǥ�ô� Blink 3ȸ������
				if (msgNum == 5) 				// Stage Clear�̸�
					synchronized (mHolder) {
						MakeNextStage();		// ���� Stage�� �����
					}
				msgLoop = 0;
				msgNum = 0;
			}	
		}
		
		//-------------------------------------
		//  ��� ��� - run()���� ȣ�� 
		//-------------------------------------
		public void DrawAll(Canvas canvas) {
			// ��� �̹���
			canvas.drawBitmap(imgBack, 0, 0, null);
			
			// �̵�Ƚ�� & Stage & ����ð� ���
			mScore.MakeTime(startTime);
			canvas.drawBitmap(mScore.imgStage, Width / 2 - mScore.imgStage.getWidth() / 2, 15, null);
			canvas.drawBitmap(mScore.imgTime, Width - mScore.imgTime.getWidth() - 15, 15, null);
			
			// Slice ǥ��
			for (int i = 0; i < sMax; i++)
				canvas.drawBitmap(mSlice[i].imgPic, mSlice[i].x, mSlice[i].y, null);
		}
		
		//-------------------------------------
		//  ������ ��ü
		//-------------------------------------
		public void run() {
			Canvas canvas = null; 					// canvas�� �����
			while (canRun) {
				canvas = mHolder.lockCanvas();		// canvas�� ��װ� ���� �Ҵ�
				try {
					synchronized (mHolder) {
						DrawAll(canvas);				// ��� ���
						if (msgNum > 0) DrawMessage(canvas);	// �޽��� ���	
					}
				} finally {								// ���� �۾��� ������ 
					if (canvas != null)					// ������ ������ View�� ���
						mHolder.unlockCanvasAndPost(canvas);
				} // try

				// ������ �Ͻ� ���� 
				synchronized (this) {
            		if (isWait)				// Pause ����̸�
            			try {
            				wait();			// ������ ���
            			} catch (Exception e) {
							// nothing
						}
    			} // sync
				
			} // while
		} // run
	
		//-------------------------------------
		//  ������ ���� ����
		//-------------------------------------
		public void StopThread() {
			canRun = false;
        	synchronized (this) {
        		this.notify();
			}
		}
		
		//-------------------------------------
		//  ������ �Ͻ����� / ��⵿
		//-------------------------------------
		public void PauseNResume(boolean wait) { 
			isWait = wait;
        	synchronized (this) {
        		this.notify();
			}
		}
	} // GameThread ��
	
	//-------------------------------------
	//  onTouch Event 
	//-------------------------------------
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			int x = (int) event.getX(); 
			int y = (int) event.getY();
			synchronized(mHolder)  {
				if (mRect.contains(x, y)){ 
					//
				}
			}
		}
		return true;
	} // Touch

} // SurfaceView 
